import request from '@/utils/request'

export const getChat = (messageContent) => {
  return request({
    method: 'GET',
    url: '/aliyun/ask',
    params: {
      inputValue:messageContent
    }
  })
}

export const saveHistory =  (historyData) => {
  return request({
    url: '/wlxz/historychat',
    method: 'POST',
    data: {
      userId: historyData.userId,
      chatId: historyData.chatId,
      ask: historyData.ask,
      request: historyData.request.replace(/\n/g, ' ').trim()
    }
  })
}

// 删除历史对话
export function deleteHistoryChat(chatId) {
  return request({
    url: `/wlxz/historychat/${chatId}`,
    method: 'put'
  })
}

// 获取历史对话列表
export function getHistoryList() {
  return request({
    url: '/wlxz/historychat/list',
    method: 'get'
  })
}

// 获取指定天数的历史聊天统计数据
export function getHistoryChatCount(days, deptId) {
  return request({
    url: '/wlxz/historychat/count',
    method: 'get',
    params: {
      days,
      deptId
    }
  })
}

/**
 * 请求阿里云问答的 SSE 流
 * @param {string} question - 用户输入的问题
 * @param {string} token - 用户的认证令牌
 * @returns {Promise<Response>} - 原生 fetch 返回的 Response 对象(流模式)
 */
export function askAliyunStream(question, token) {
  return fetch(
    `/dev-api/aliyun/ask?inputValue=${encodeURIComponent(question)}`,
    {
      method: "GET",
      headers: {
        Authorization: token ? `Bearer ${token}` : "",
        Accept: "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive",
      },
    }
  );
}

/**
 * 获取词云数据
 * @param {number} days - 天数
 * @returns {Promise} - 返回词云数据
 */
export function getWordCloudData(days) {
  return request({
    url: '/wlxz/historychat/wordcloud',
    method: 'get',
    params: { days }
  })
}

// 添加停止词
export function addStopWords(words) {
  const params = new URLSearchParams();
  words.forEach(word => {
    params.append('words', word);
  });
  
  return request({
    url: '/wlxz/stopWords/words',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: params
  })
}
